import React from 'react';
import { Tag, Input, Tooltip, Icon, message } from 'antd';
import { returnAtIndex } from 'lodash-decorators/utils';

class EditTag extends React.Component{
  state = {
    tags: this.props.tags,
    inputVisible: false,
    inputValue: '',
    checkValue:{
      state:true,
      message:''
    }
  };

  componentDidMount() {
    if(this.props.onRef){
      this.props.onRef(this);
    }
  }

  handleClose = removedTag => {
    const tags = this.state.tags.filter(tag => tag !== removedTag);
    this.setState({ tags });
  };

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  };

  handleInputChange = e => {
    this.setState({ inputValue: e.target.value });
  };

  handleInputConfirm = () => {
    const { inputValue } = this.state;
    let { tags } = this.state;
    let dealtedValue = inputValue.replace(/[,，:：;；''""“”’‘{}【】\[\]\\、。.|？?<>《》/!！%]/g, "");
    if (dealtedValue.length > 20) {
      this.setState({
        checkValue:{
          state:false,
          message:'同义词不可超过20个字符'
        }
      })
      return message.error({ content: '同义词不可超过20个字符', key:'synonym' });
    }else {
      this.setState({
        checkValue:{
          state:true,
          message:''
        }
      })
    }
    if (dealtedValue.trim() && tags.indexOf(dealtedValue) === -1) {
      tags = [dealtedValue.trim(),...tags];
    }
    this.setState({
      tags,
      inputVisible: false,
      inputValue: '',
    });
  };

  saveInputRef = input => (this.input = input);

  render() {
    const { tags, inputVisible, inputValue } = this.state;
    return (
      <div>
        {inputVisible && (
          <Input
            ref={this.saveInputRef}
            type="text"
            size="small"
            style={{ width: 78 }}
            value={inputValue}
            onChange={this.handleInputChange}
            onBlur={this.handleInputConfirm}
            onPressEnter={this.handleInputConfirm}
          />
        )}
        {!inputVisible && (
          <Tag onClick={this.showInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
            <Icon type="plus" /> 添加同义词
          </Tag>
        )}
        {tags.map((tag, index) => {
          const isLongTag = tag.length > 20;
          let color = index % 2 == 1 ? '#87d3ac' : '#5092e1';
          const tagElem = (
            <Tag key={tag} closable onClose={() => this.handleClose(tag)} color={color}>
              {isLongTag ? `${tag.slice(0, 20)}...` : tag}
            </Tag>
          );
          return isLongTag ? (
            <Tooltip title={tag} key={tag}>
              {tagElem}
            </Tooltip>
          ) : (
            tagElem
          );
        })}
      </div>
    )
  }
}

export default EditTag;
